from sqlalchemy.orm import Session
from schema import Farming_Operation_schema
from model import Farming_Operation_model



def get_Farming_Operation(db: Session, ID: int):
    return db.query(Farming_Operation_model.Farming_operation).filter(Farming_Operation_model.Farming_operation.ID == ID).first()


def get_all_Farming_Operation(db: Session):
    return db.query(Farming_Operation_model.Farming_operation).all()


def delete_Farming_Operation(db: Session, ID):
    to_delete = db.query(Farming_Operation_model.Farming_operation).filter(Farming_Operation_model.Farming_operation.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Farming_Operation(db: Session, Farming_Operation: Farming_Operation_schema.Farming_operation):
    db_Farming_Operation = Farming_Operation_model.Farming_operation(
        OperationName=Farming_Operation.OperationName,
        OperationType=Farming_Operation.OperationType,
        StartTime=Farming_Operation.StartTime,
        EndTime=Farming_Operation.EndTime,
        Status=Farming_Operation.Status,
        Remarks=Farming_Operation.Remarks,
    )
    db.add(db_Farming_Operation)
    db.commit()
    db.refresh(db_Farming_Operation)
    return db_Farming_Operation


def update_Farming_Operation(db: Session, ID, field_name, new_value):
    db_Farming_Operation = db.query(Farming_Operation_model.Farming_operation).filter(Farming_Operation_model.Farming_operation.ID == ID).first()
    setattr(db_Farming_Operation, field_name, new_value)
    db.commit()
    db.refresh(db_Farming_Operation)
    return db_Farming_Operation
